// page/component/orders/orders.js
Page({
  data:{
    address:{},
    hasAddress: false,
    total:0,
    orders:[
        {id:1,title:'新鲜芹菜 半斤',image:'/image/s5.png',num:4,price:0.01},
        {id:2,title:'素米 500g',image:'/image/s6.png',num:1,price:0.03}
      ]
  },

  onReady() {
    this.getTotalPrice();
  },
  
  onShow:function(){
    const self = this;
    wx.getStorage({
      key:'address',
      success(res) {
        self.setData({
          address: res.data,
          hasAddress: true
        })
      }
    })
  },
  onLoad(){
    var orders = wx.getStorageSync('toBuy')
    this.setData({
      orders
    })
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let orders = this.data.orders;
    let total = 0;
    for(let i = 0; i < orders.length; i++) {
      total += orders[i].num * orders[i].price;
    }
    this.setData({
      total: total
    })
  },

  toPay() {
    var uid = wx.getStorageSync('openid')
    var toBuy = wx.getStorageSync('toBuy')
    var len = toBuy.length
    console.log(len)
    wx.cloud.callFunction({
      name:"addOrders",
      data:{
        uid:uid,
        goods:toBuy,
        total:this.data.total,
        num:len
      }
    }).then(res=>{
      console.log(res)
      var toBuy = wx.getStorageSync('toBuy')
      // var pids = []
      for(var x = 0; x < toBuy.length; x++){
        // pids.push(toBuy[x]._id)
        var pids = toBuy[x]._id
        wx.cloud.callFunction({
          name:"delPro",
          data:{
            pids:pids,
            uid:uid
          }
        })
      }
      wx.showToast({
        title: '购物完成',
      })
      wx.switchTab({
        url: '../user/user',
      })
    })

  }
})